import pandas as pd
from lxml import etree
import time

def xml_to_csv(xml_path, csv_path):
    start_time = time.time()
    data = []
    try:
        context = etree.iterparse(xml_path, events=('end',), tag='BinClassesParameterItem')
        for event, elem in context:
            item_data = {}
            for child in elem:
                if child.tag != 'Judge':
                    item_data[child.tag] = child.text
                else:
                    judge_items = child.findall('BinClassesJudgeItem')
                    for i, judge_item in enumerate(judge_items):
                        for sub_child in judge_item:
                            item_data[f'Judge_{i}_{sub_child.tag}'] = sub_child.text
            data.append(item_data)
            # 清理元素以释放内存
            elem.clear()
            while elem.getprevious() is not None:
                del elem.getparent()[0]
        del context

        # 转换为 pandas 数据框
        df = pd.DataFrame(data)

        # 写入 CSV 文件
        df.to_csv(csv_path, index=False, chunksize=1000)
        print(f"数据已成功写入 {csv_path}")
    except Exception as e:
        print(f"处理过程中出现错误: {e}")
    end_time = time.time()
    elapsed_time = end_time - start_time
    print(f"程序运行用时: {elapsed_time} 秒")

if __name__ == "__main__":
    xml_path = "kk.xml"
    csv_path = "output.csv"
    xml_to_csv(xml_path, csv_path)